package net.maku.framework.common.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.ArrayList;
import java.util.List;
/**
 * @FileName: ConvertUtil
 * @Project: malu-boot
 * @Package: net.lab1024.sa.admin.util
 * @Author: Aili
 * @Date: 2024/7/8 13:54
 * @Version: 1.0.0
 * @Description: ConvertUtil Description
 */
public class ConvertUtil {
    private static final HanyuPinyinOutputFormat DEFAULT_FORMAT = new HanyuPinyinOutputFormat();
    static {
        DEFAULT_FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        DEFAULT_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        DEFAULT_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
    }
    /**
     * 将汉字转换为拼音首字母大写
     * @param str 需要转换的字符串
     * @param length 最多取几个字符的拼音首字母
     * @return 拼音首字母大写字符串
     */
    @SuppressWarnings("all")
    public static String getUppercaseFirstLetter(String str, int length) {
        List<String> pinyinList = new ArrayList<>();
        for (int i = 0; i < Math.min(str.length(), length); i++) {
            char c = str.charAt(i);
            if (c >=  '\u4e00'  && c <= '\u9fff') { // 判断是否为汉字
                try {
                    String pinyin = PinyinHelper.toHanyuPinyinStringArray(c, DEFAULT_FORMAT)[0];
                    pinyinList.add(pinyin.substring(0, 1).toUpperCase()); // 取第一个字母并转为大写
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    throw new RuntimeException("拼音转换失败", e);
                }
            } else {
                pinyinList.add(String.valueOf(c).toUpperCase()); // 非汉字字符直接转为大写
            }
        }
        // 如果拼音首字母列表长度小于指定长度，则用 "0" 补齐
        while (pinyinList.size() < length) {
            pinyinList.add("0");
        }

        return String.join("", pinyinList.subList(0, length));
    }
}
